<script setup>
import { h, ref, onMounted } from 'vue'
import { NButton, NSpace, useMessage, NModal, NForm, NFormItem, NUpload, NIcon, NTag, NSpin } from 'naive-ui'
import { ImportOutlined } from '@vicons/antd'
import moment from 'moment'
import CrudTable from '@/components/CrudTable/index.vue'
import WangEditor from '@/components/WangEditor/index.vue'
import request from '@/utils/request'
import { saveAs } from 'file-saver'

const message = useMessage()
const crudTableRef = ref(null)

// 添加分类选项
const categories = ref([])

// 获取分类字典
const fetchCategories = async () => {
  const res = await request.get('/dictionary-details/help_question_category')
  categories.value = res.map(item => ({
    label: item.dict_value,
    value: item.dict_key
  }))
}

// 在组件挂载时获取分类
onMounted(() => {
  fetchCategories()
})

// 导入相关
const showImportModal = ref(false)
const importLoading = ref(false)
const uploadLoading = ref(false)
const importFormRef = ref(null)
const importForm = ref({
  file: null
})

// 导入表单验证规则
const importRules = {
  file: {
    required: true,
    message: '请选择Excel文件',
    validator: (rule, value) => {
      if (!value) return new Error('请选择Excel文件')
      if (!value.file) return new Error('文件上传失败')

      const fileName = value.file.name.toLowerCase()
      const isExcel = /\.(xlsx|xls)$/.test(fileName)
      if (!isExcel) {
        return new Error('只支持.xlsx、.xls格式的Excel文件')
      }

      const maxSize = 10 * 1024 * 1024 // 10MB
      if (value.file.size > maxSize) {
        return new Error('文件大小不能超过10MB')
      }

      return true
    },
    trigger: ['change']
  }
}

// 处理文件上传改变
const handleUploadChange = async ({ file }) => {
  try {
    if (!file || !file.file) {
      message.error('文件上传失败')
      return
    }

    const fileName = file.file.name.toLowerCase()
    const isExcel = /\.(xlsx|xls)$/.test(fileName)

    if (!isExcel) {
      message.error('只支持.xlsx、.xls格式的Excel文件')
      return
    }

    const maxSize = 10 * 1024 * 1024 // 10MB
    if (file.file.size > maxSize) {
      message.error('文件大小不能超过10MB')
      return
    }

    uploadLoading.value = true
    importForm.value.file = file
  } finally {
    uploadLoading.value = false
  }
}

// 下载导入模板
const downloadTemplate = async () => {
  try {
    // 创建模板数据
    const templateData = [
      ['标题', '答案', '分类'],
      ['Vue生命周期有哪些？', '创建、挂载、更新、销毁...', 'vue'],
      ['什么是闭包？', '闭包是指有权访问另一个函数作用域中变量的函数...', 'javascript']
    ]

    // 使用 XLSX 库创建工作簿
    const XLSX = await import('xlsx')
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.aoa_to_sheet(templateData)

    // 设置列宽
    ws['!cols'] = [
      { wch: 30 }, // 标题列宽
      { wch: 50 }, // 答案列宽
      { wch: 15 }, // 分类列宽
      { wch: 20 }  // 标签列宽
    ]

    XLSX.utils.book_append_sheet(wb, ws, '面试题导入模板')

    // 生成Excel文件并下载
    XLSX.writeFile(wb, '面试题导入模板.xlsx')
  } catch (error) {
    message.error('模板下载失败')
  }
}

// 处理导入提交
const handleImportSubmit = async () => {
  try {
    await importFormRef.value?.validate()
    importLoading.value = true
    const formData = new FormData()
    formData.append('file', importForm.value.file.file)

    await request.post('/interview-questions/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    message.success('导入成功')
    showImportModal.value = false
    importForm.value.file = null
    crudTableRef.value?.fetchData()
  } finally {
    importLoading.value = false
  }
}

// 打开导入弹窗
const handleImport = () => {
  showImportModal.value = true
}

// 移除固定的categoryTagTypes映射
// 改为使用随机标签类型函数
const getRandomTagType = (() => {
  const types = ['primary']
  const cache = new Map()

  return (category) => {
    if (!cache.has(category)) {
      const randomType = types[Math.floor(Math.random() * types.length)]
      cache.set(category, randomType)
    }
    return cache.get(category)
  }
})()

const questionConfig = ref({
  title: '帮助中心',
  apiPrefix: '/help_questions',
  primaryKey: 'id',

  // 启用搜索
  switchable:true,
  switchKey:'status',
  searchable: true,
  searchFields: [
    {
      label: '标题',
      key: 'question_title',
      type: 'input',
    },
    {
      label: '分类',
      key: 'category',
      type: 'select',
      options: categories,
    },
  ],

  // 启用基础操作
  creatable: true,
  editable: true,
  deletable: true,

  // 表格配置
  tableConfig: {
    pagination: true,
    bordered: false,
    size: 'medium',
    scrollX: 1400
  },

  // 表单配置
  formConfig: {
    width: '1000px',
    labelWidth: 100,
    labelPlacement: 'left',
    requireMarkPlacement: 'right-hanging'
  },

  // 表格列配置
  columns: [
    {
      title: '标题',
      key: 'question_title',
      ellipsis: true
    },
    {
      title: '分类',
      key: 'category',
      ellipsis: true,
      render: (row) => {
        const category = categories.value.find(c => c.value === row.category)
        if (!category) return null

        return h(NTag, {
          type: getRandomTagType(category.value),
          size: 'small',
          round: true,
          bordered: false,
          style: {
            marginRight: '6px'
          }
        }, {
          default: () => category.label
        })
      }
    },

    {
      title: '创建时间',
      key: 'created_at',
      render: (row) => {
        return row.created_at && moment(row.created_at).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    {
      title: '更新时间',
      key: 'updated_at',
      render: (row) => {
        return row.updated_at && moment(row.updated_at).format('YYYY-MM-DD HH:mm:ss')
      }
    }
  ],

  // 添加表单验证规则
  rules: {
    question_title: [
      { required: true, message: '请输入面试题标题' },
      { max: 500, message: '标题长度不能超过500个字符' }
    ],
    question_answer: [
      { required: false, message: '请输入面试题答案' },
      { max: 10000, message: '答案长度不能超过10000个字符' }
    ],
    category: [
      { required: true, message: '请选择分类' }
    ],

  },

  // 修改表单字段配置，移除重复的rules
  formFields: [
    {
      label: '标题',
      key: 'question_title',
      type: 'input',
      span: 24,
      required: true
    },
    {
      label: '答案',
      key: 'question_answer',
      type: 'custom',
      span: 24,
      required: true,
      render: ({ value, onChange }) => {
        return h(WangEditor, {
          value,
          'onUpdate:value': onChange,
          height: 400
        })
      }
    },
    {
      label: '分类',
      key: 'category',
      type: 'select',
      options: categories,
      span: 12,
      required: true
    },

  ]
})
</script>

<template>
  <div style="height: 100%;">
    <crud-table ref="crudTableRef" :config="questionConfig">
      <!-- 添加导入按钮到表格头部 -->
      <template #table-header-left>
        <n-button
          @click="handleImport"
          class="custom-button"
          quaternary
        >
          <template #icon>
            <n-icon>
              <import-outlined />
            </n-icon>
          </template>
          导入
        </n-button>
      </template>
    </crud-table>

    <!-- 导入弹窗 -->
    <n-modal
      v-model:show="showImportModal"
      :mask-closable="false"
      preset="card"
      title="导入面试题"
      style="width: 600px"
      size="small"
    >
      <n-spin :show="uploadLoading">
        <n-form
          ref="importFormRef"
          :model="importForm"
          :rules="importRules"
          label-placement="left"
          label-width="100"
          require-mark-placement="right-hanging"
        >
          <n-form-item label="Excel文件" path="file">
            <n-upload
              accept=".xlsx,.xls"
              :default-upload="false"
              :max="1"
              :disabled="uploadLoading || importLoading"
              @change="handleUploadChange"
            >
              <n-button :disabled="uploadLoading || importLoading">
                选择文件
              </n-button>
            </n-upload>
          </n-form-item>
          <n-form-item label="下载模板">
            <n-space vertical>
              <n-button
                type="primary"
                @click="downloadTemplate"
                :disabled="uploadLoading || importLoading"
              >
                下载导入模板
              </n-button>
              <span>请按模板格式填写，标题为必填项</span>
            </n-space>
          </n-form-item>
        </n-form>
      </n-spin>
      <template #footer>
        <n-space justify="end">
          <n-button
            @click="showImportModal = false"
            :disabled="uploadLoading || importLoading"
          >
            取消
          </n-button>
          <n-button
            type="primary"
            :loading="importLoading"
            :disabled="!importForm.file || uploadLoading"
            @click="handleImportSubmit"
          >
            确定导入
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<style lang="scss" scoped>
:deep(.wang-editor) {
  margin-bottom: 24px;
  min-height: 450px;

  .editor-content {
    width: 100%;
  }
}

.custom-button {
  margin-right: 12px;
}

:deep(.n-tag) {
  padding: 2px 10px;
  font-size: 12px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

:deep(.n-tag) {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
